﻿using System.Text.Json;
using K9Nano.Exceptions;

namespace K9Nano.Reporting;

public class Report
{
    public const string PageSizeParameterName = "@pageSize";
    public const string OffsetParameterName = "@offset";

    /// <summary>
    /// 报表ID
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// 报表名称
    /// </summary>
    public string DisplayName { get; set; }

    public string Description { get; set; }

    /// <summary>
    /// 查询总数据量的SQL语句
    /// </summary>
    public string TotalSqlText { get; set; }

    /// <summary>
    /// 查询当前页数据的SQL语句
    /// </summary>
    public string SqlText { get; set; }

    /// <summary>
    /// 参数信息
    /// </summary>
    public List<ReportFormItem> FormItems { get; set; }

    /// <summary>
    /// 列信息
    /// </summary>
    public List<ReportColumn> Columns { get; set; }

    /// <summary>
    /// 是否启用
    /// </summary>
    public bool IsEnabled { get; set; }

    public IReadOnlyDictionary<string, object> PrepareReportParameters(
        int pageIndex,
        int pageSize,
        IReadOnlyDictionary<string, object> raw)
    {
        var result = new Dictionary<string, object>
        {
            { PageSizeParameterName, pageSize > 0 ? pageSize :int.MaxValue },
            { OffsetParameterName,  pageIndex> 0 ? (pageIndex -1) * pageSize : 0 },
        };

        foreach (var field in FormItems)
        {
            if (!raw.TryGetValue(field.Name, out var rawValue))
            {
                // 使用默认参数
                result[field.Name] = field.GetDefaultSqlValue();
                continue; ;
            }
            if (rawValue is JsonElement jsonElement)
            {
                result[field.Name] = field.GetSqlValue(jsonElement);
            }
            else
            {
                result[field.Name] = rawValue;
            }
        }

        return result;
    }
}
